package client

import (
	"strings"
	"yunj/app/enum/articleenum"
	"yunj/app/service"
	blogService "yunj/app/service/client"
	"yunj/pkg/global"
	"yunj/pkg/util"
	yunjUtil "yunj/pkg/yunj/util"

	"github.com/gin-gonic/gin"
)

type Category struct {
	Controller
}

// 分类页
func (ctrl *Category) Index(c *gin.Context) {
	// 接收参数。兼容.html后缀格式
	idStr := yunjUtil.PathParam(c, "id")
	idStr = strings.TrimSuffix(idStr, ".html")
	id, err := yunjUtil.ToUint64(idStr)
	if err != nil || id <= 0 {
		util.RedirectError(c, "异常分类数据访问！")
		return
	}
	// 获取当前分类
	category := service.Category.GetItemNormalById(id)
	if category.Id == 0 {
		util.RedirectError(c, "分类数据异常")
		return
	}
	// 获取文章列表数据
	params := blogService.ArticlePageListParams{
		Page:        1,
		PageSize:    8,
		Keywords:    "",
		CategoryIds: []uint64{category.Id},
		SortRule:    articleenum.SORT_RULE_HOT,
	}
	if category.Alias == global.Config.Default.Category.Alias {
		// 兼容旧有数据
		params.CategoryIds = append(params.CategoryIds, uint64(0))
	}
	pageData := blogService.Article.PageList(params)
	// 组装渲染数据
	data := map[string]interface{}{
		"category":        category,
		"sortRule":        articleenum.SORT_RULE_HOT,
		"articlePageData": pageData,
	}
	ctrl.Render(c, "category/index", data)
}
